package leetcode_201_300;

import node.TreeNode;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class LeeCode_235 {
    public static void main(String[] args) {

    }
    private static TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        List<TreeNode> pathP = new ArrayList<>();
        List<TreeNode> pathQ = new ArrayList<>();
        search(root, pathP, p.val);
        search(root, pathQ, q.val);
        Set<TreeNode> setP = new HashSet<>(pathP);
        for (int i = pathQ.size() - 1; i >= 0; i--) {
            TreeNode node = pathQ.get(i);
            if (setP.contains(node)){
                return node;
            }
        }
        return null;
    }
    private static void search(TreeNode node, List<TreeNode> list, int goal){
        if (node == null)
            return;
        list.add(node);
        if (goal == node.val){
            return;
        }
        if (goal < node.val){
            search(node.left, list, goal);
        }else {
            search(node.right, list, goal);
        }
    }
}
